/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cestum.cave.presenter.wave.utils {
import com.hurlant.crypto.prng.Random;

import org.goverla.utils.Maths;
import org.waveprotocol.wave.model.util.StringBuilder;

public class RandomBase64Generator {
	
	/** The 64 valid web-safe characters. */
	static var WEB64_ALPHABET:Array=
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split("");
	
	private var random:Random;
	
	/**
	 * @param random Pseudo-random generator,
	 *        use Random for speed, SecureRandom for cryptographic strength.
	 */
	public function RandomBase64Generator(_random:Random = null) {
		if (_random == null) {
			this.random = new Random();
		} else 
			this.random = _random;
	}
	/**
	 * @param length The requested number of random base 64 characters.
	 * @return string with length many random base 64 characters.
	 */
	public function next(length:int):String {
		var result:StringBuilder= new StringBuilder();
		var bits:int= 0;
		var bitCount:int= 0;
		while (result.length() < length) {
			if (bitCount < 6) {
				bits = Maths.random(65535);
				bitCount = 32;
			}
			result.append(WEB64_ALPHABET[bits & 0x3F]);
			bits >>= 6;
			bitCount -= 6;
		}
		return result.toString();
	}
}
}